package com.deyun.smartairporthandset.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Camera;
import android.media.FaceDetector;
import android.os.Bundle;
import android.os.Environment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.bifan.detectlib.FaceDetectTextureView;
import com.bifan.detectlib.FaceDetectView;
import com.deyun.smartairporthandset.MainActivity;
import com.deyun.smartairporthandset.R;
import com.deyun.smartairporthandset.adapter.TestAdapter;
import com.deyun.smartairporthandset.entity.TestEntity;
import com.deyun.smartairporthandset.util.SharedPreferenceUtil;
import com.example.zhouwei.library.CustomPopWindow;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class IdRegFragment extends Fragment {


    private Unbinder unbinder;

    @BindView(R.id.faceDetectView)
    FaceDetectView faceDetectView;
    @BindView(R.id.tv_scan)
    TextView tv_scan;
    @BindView(R.id.tv_enter)
    TextView tv_enter;
    @BindView(R.id.tv_exit)
    TextView tv_exit;
    @BindView(R.id.tv_select_section)
    TextView tv_select_section;
    @BindView(R.id.rl_main)
    RelativeLayout rl_main;
    @BindView(R.id.rl_id_reg)
    RelativeLayout rl_id_reg;
    @BindView(R.id.rl_reg_result)
    RelativeLayout rl_reg_result;
    @BindView(R.id.tv_confirm_pass)
    TextView tv_confirm_pass;
    @BindView(R.id.tv_nucleate)
    TextView tv_nucleate;
    @BindView(R.id.rl_reg_result_info)
    RelativeLayout rl_reg_result_info;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_nucleate_date)
    TextView tv_nucleate_date;


    public ArrayList<TestEntity> al;
    public TestAdapter testAdapter;
    public CustomPopWindow sectionPopWindow;

    public MainActivity mainActivity;

    public boolean is_Scan = false;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private boolean isSavingPic = false;
    // 防止重复提交图片到服务器和持续保存人脸图片到本地
    private boolean isSubmitToServer = false;

    private class SavePicRunnable implements Runnable {
        Bitmap bitmap;

        SavePicRunnable(Bitmap bitmap) {
            this.bitmap = bitmap;
            isSavingPic = false;
            saveFacePicToLocal(bitmap);
        }

        @Override
        public void run() {
            isSavingPic = false;
        }
    }

    @OnClick({R.id.tv_scan, R.id.tv_enter, R.id.tv_exit, R.id.tv_select_section, R.id.tv_test, R.id.tv_test1, R.id.tv_confirm_pass})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_scan:
                if (!is_Scan) {
                    faceDetectView.setVisibility(View.VISIBLE);
                    //必须是在view可见后进行初始化
                    faceDetectView.initView();
                    faceDetectView.initCamera();
                    faceDetectView.getDetectConfig().CameraType = Camera.CameraInfo.CAMERA_FACING_FRONT;
                    faceDetectView.getDetectConfig().EnableFaceDetect = true;
                    faceDetectView.getDetectConfig().MinDetectTime = 2000;
                    faceDetectView.getDetectConfig().Simple = 0.5f;//图片检测时的压缩取样率，0~1，越小检测越流畅
                    faceDetectView.getDetectConfig().MaxDetectTime = 5000;//进入智能休眠检测，以2秒一次的这个速度检测
                    faceDetectView.getDetectConfig().EnableIdleSleepOption = false;//不启用智能休眠检测机制
                    faceDetectView.getDetectConfig().IdleSleepOptionJudgeTime = 1000 * 10;//1分钟内没有检测到人脸，进入智能休眠检测
                    faceDetectView.startCameraPreview();
                    tv_scan.setText("关闭人脸识别");
                    is_Scan = !is_Scan;
                } else {
                    closeFaceReg();
                }
                break;
            case R.id.tv_enter:
                tv_enter.setBackgroundResource(R.drawable.corner_blue5_left);
                tv_enter.setTextColor(getActivity().getResources().getColor(R.color.white));
                tv_exit.setBackgroundResource(R.drawable.corner_blue5_bord_right);
                tv_exit.setTextColor(getActivity().getResources().getColor(R.color.black));
                break;
            case R.id.tv_exit:
                tv_enter.setBackgroundResource(R.drawable.corner_blue5_bord_left);
                tv_enter.setTextColor(getActivity().getResources().getColor(R.color.black));
                tv_exit.setBackgroundResource(R.drawable.corner_blue5_right);
                tv_exit.setTextColor(getActivity().getResources().getColor(R.color.white));
                break;
            case R.id.tv_select_section:
                showPop();
                break;
            case R.id.tv_test:
                showPassInfo();
                break;
            case R.id.tv_test1:
                // 不通过的显示
                showNoPassInfo();
                break;
            case R.id.tv_confirm_pass:
                rl_id_reg.setVisibility(View.VISIBLE);
                rl_reg_result.setVisibility(View.INVISIBLE);
                break;
        }
    }


    // 保存人脸图片到本地
    private void saveFacePicToLocal(Bitmap bitmap) {
        LogUtils.d("检测到人脸，图片正在保存到本地");

        String picPath = Environment.getExternalStorageDirectory() + "/face.jpg";
        FileOutputStream fileOutputStream = null;
        File facePicFile = new File(picPath);
        try {
            facePicFile.createNewFile();
        } catch (IOException e) {
            LogUtils.d("保存失败" + e.toString() + "," + picPath);
            e.printStackTrace();
        }
        try {
            fileOutputStream = new FileOutputStream(facePicFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (fileOutputStream != null) {
            BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        bitmap.recycle();
        // upLoadImage(facePicFile);

    }


    public void showNoPassInfo() {
        rl_id_reg.setVisibility(View.INVISIBLE);
        rl_reg_result.setVisibility(View.VISIBLE);
        rl_reg_result_info.setBackgroundResource(R.drawable.corner_light_red5_bord);
        tv_title.setTextColor(getResources().getColor(R.color.Red));
        tv_title.setText("扫码异常");
        // 指定汉字显示指定颜色
        SpannableString spannableString = new SpannableString("核酸检测: 检测过期");
        SpannableString spannableString_date = new SpannableString("核酸有效期: 2021-01-31");
        // 设置要显示的颜色
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#DC143C"));
        spannableString.setSpan(colorSpan, 6, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString_date.setSpan(colorSpan, 7, spannableString_date.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_nucleate.setText(spannableString);
        tv_nucleate_date.setText(spannableString_date);
        tv_confirm_pass.setText("返回重扫");
    }


    public void showPassInfo() {
        rl_id_reg.setVisibility(View.INVISIBLE);
        rl_reg_result.setVisibility(View.VISIBLE);
        rl_reg_result_info.setBackgroundResource(R.drawable.corner_light_green5_bord);
        tv_title.setTextColor(getResources().getColor(R.color.Green));
        tv_title.setText("检验通过");
        // 指定汉字显示指定颜色
        SpannableString spannableString = new SpannableString("核酸检测: 检测有效");
        // 设置要显示的颜色
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#32CD32"));
        spannableString.setSpan(colorSpan, 6, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_nucleate.setText(spannableString);
        tv_nucleate_date.setText("核酸有效期: 2021-01-31");
        tv_confirm_pass.setText("确认通过");
    }


    public void closeFaceReg() {
        if (faceDetectView != null && faceDetectView.isHasInit()) {
            faceDetectView.stopCameraPreview();
            faceDetectView.getFaceRectView().clearBorder();
            faceDetectView.setVisibility(View.INVISIBLE);
            tv_scan.setText("开始人脸识别");
            is_Scan = !is_Scan;
        }
    }


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public IdRegFragment() {

    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static IdRegFragment newInstance(String param1, String param2) {
        IdRegFragment fragment = new IdRegFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_id_reg, container, false);
        mainActivity = (MainActivity) getActivity();
        unbinder = ButterKnife.bind(this, v);
        tv_enter.setBackgroundResource(R.drawable.corner_blue5_left);
        tv_enter.setTextColor(getActivity().getResources().getColor(R.color.white));

        //测试数据
        al = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            TestEntity testEntity = new TestEntity(i, false, "测试区域" + i);
            al.add(testEntity);
        }


        String str_sectionName = SharedPreferenceUtil.getString(getActivity(), "SectionName", "");
        if (!str_sectionName.equals("")) {
            mainActivity.sectionName = str_sectionName;
            tv_select_section.setText(str_sectionName);
            for (int i = 0; i < al.size(); i++) {
                if (str_sectionName.equals(al.get(i).getName())) {
                    al.get(i).setCheck(true);
                }
            }
        }

        testAdapter = new TestAdapter(al, getActivity());

        faceDetectView.setFramePreViewListener(new FaceDetectTextureView.IFramePreViewListener() {
            @Override
            public boolean onFrame(Bitmap preFrame) {
                //每一帧回调
                //这个这帧preFrame处理了就是进行了回收，返回true
                //否则返回false，内部进行回收处理
                return false;
            }

            @Override
            public boolean onFaceFrame(Bitmap preFrame, FaceDetector.Face[] faces) {
                //faces是检测出来的人脸参数
                //检测到人脸的回调,保存人脸图片到本地
                if (isSavingPic == false && isSubmitToServer == false) {
                    isSavingPic = true;
                    executorService.submit(new SavePicRunnable(preFrame));
                }
                //这个这帧preFrame处理了就是进行了回收，返回true
                //否则返回false，内部进行回收处理
                return true;
            }
        });


        return v;
    }

    // 显示选择区域
    public void showPop() {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_listview, null);
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        double width = display.getWidth() * 0.9;
        double height = display.getHeight() * 0.7;
        sectionPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)//显示的布局，还可以通过设置一个View
                .size((int) width, (int) height) //设置显示的大小，不设置就默认包裹内容
                .setFocusable(false)//是否获取焦点，默认为ture
                .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setClippingEnable(false)
                .setBgDarkAlpha(0.7f) // 控制亮度
                .create()//创建PopupWindow
                .showAtLocation(rl_main, Gravity.CENTER, 0, 0);//显示PopupWindow

        ListView lv = contentView.findViewById(R.id.lv_section_info);
        lv.setAdapter(testAdapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                confirmDialog("您选中的是" + al.get(i).getName(), i);
            }
        });

    }


    public void confirmDialog(String str, final int i) {
        new AlertDialog.Builder(mainActivity).setTitle(str)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sectionPopWindow.dissmiss();
                        Toast.makeText(getActivity(), "您选中的是" + al.get(i).getName(), Toast.LENGTH_SHORT).show();
                        SharedPreferenceUtil.putString(mainActivity, "SectionName", al.get(i).getName());
                        for (int j = 0; j < al.size(); j++) {
                            al.get(j).setCheck(false);
                        }
                        al.get(i).setCheck(true);
                        tv_select_section.setText(al.get(i).getName());
                        mainActivity.sectionName = al.get(i).getName();
                    }
                })
                .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    // 设置区域名称
    public void setSectionName(String str) {
        if (tv_select_section != null) {
            tv_select_section.setText(str);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (faceDetectView != null) {
            faceDetectView.release();
        }
    }
}
